<template>
  <div class="app-container">
    <div class="grid-content ep-bg-purple" />
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公文名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入公文名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="下发时间" style="width: 308px">
        <el-date-picker v-model="daterangeSendTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coordination:offcial:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['coordination:offcial:export']">导出</el-button>
      </el-col> -->
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">

        <div class="ul">
          <div class="list" :class="item.id==selectId?'active':''" v-for="(item,index) in offcialList" :key="index" @click.stop="handleCurrentChange(item.id)">
            <div class="flex between">
              <div class="flex">
                <div class="serice">{{index+1}}</div>
                <div class="source"><el-tag :type="item.source==1?'warning':item.source==2?'success':'danger'"><dict-tag :options="coo_official_source"
                      :value="item.source" /></el-tag> </div>

                <div @click.stop="previewFun(item.fileUrl)" class="name">{{item.name}}</div>
              </div>

              <div class="flex">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(item)" v-hasPermi="['coordination:offcial:edit']"></el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(item)" v-hasPermi="['coordination:offcial:remove']"></el-button>
              </div>
            </div>
            <div class="flex between">
              <div class="demand">
                要求：<span class=""> {{item.demand?item.demand:'暂无'}}</span>
              </div>

            </div>
            <div class="absolute">
              <span class="text-theme">{{item.readNum?item.readNum:0}}</span>/{{item.readTotal}}
            </div>
            <div class="time">下发时间：{{ parseTime(item.sendTime, '{y}-{m}-{d}') }}</div>

          </div>
        </div>

        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
      <el-col :span="16">
        <div class="grid-content ep-bg-purple"></div>
        <div class="empty-top"></div>
        <el-table v-loading="loading" :data="implementList" show-overflow-tooltip @selection-change="handleSelectionChange" height="610px">
          <el-table-column type="index" width="65" label="序号" align="center" />
          <el-table-column label="收费站" align="center" prop="deptName" />
          <el-table-column label="已读/未读" align="center" prop="status" width="180" sortable>
            <template #default="scope">
              <span>{{ scope.row.status==1?'已读':'未读' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="落实类型" align="center" prop="implType">
            <template #default="scope">
              <dict-tag :options="coo_impl_type" :value="scope.row.implType" />
            </template>
          </el-table-column>

          <el-table-column label="落实描述" align="center" prop="implDescribe" />

          <el-table-column label="印证资料" align="center" prop="proof">
            <template #default="scope">
              <el-button link type="primary" @click.stop="previewFun(scope.row.proof)" v-if="scope.row.proof">查看</el-button> </template>
          </el-table-column>

          <el-table-column label="证明人" align="center" prop="certifierName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleShow(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
    </el-row>

    <!-- 添加或修改公文管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="offcialRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公文名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入公文名称" />
        </el-form-item>
        <el-form-item label="公文来源" prop="source">
          <el-select style="width:100%" v-model="form.source" placeholder="请选择公文来源" @change="bindChangeSelect">
            <el-option v-for="dict in coo_official_source" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="下发时间" prop="sendTime">
          <el-date-picker style="width:100%" clearable v-model="form.sendTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择下发时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收费站" prop="deptIds">
          <div>
            <el-radio-group v-model="radioDept" size="large" class="margin-bottom">
              <el-radio-button label="全部收费站" :value="1" />
              <el-radio-button label="部分收费站" :value="2" />
            </el-radio-group>
            <el-transfer v-model="form.deptIds" v-if="radioDept=='部分收费站'" :data="deptOptions" :titles="['收费站', '文件下发站']" />
          </div>
        </el-form-item>
        <el-form-item label="文件" prop="fileUrl">
          <FileUpload :modelValue="form.fileUrl" v-model="form.fileUrl" />
        </el-form-item>
        <el-form-item label="要求" prop="demand">
          <el-input v-model="form.demand" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="站级公文管理详情" v-model="isShow" width="1200px" append-to-body>

      <el-form ref="implementRef" :model="formShow" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="收费站" prop="deptName">
              <el-input style="width:100%" v-model="formShow.deptName" placeholder="暂无" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已读/未读" prop="status"  label-width="120" >
              <el-input style="width:100%" v-model="formShow.status" :value="formShow.status==1?'已读':'未读'" placeholder="暂无" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="落实类型" prop="implType">
              <el-select style="width:100%" v-model="formShow.implType" placeholder="暂无" :disabled="true">
                <el-option v-for="dict in coo_impl_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item style="width:100%" label-width="120" label="参会人员数" prop="attendeeNo" v-if="formShow.implType==1||(!formShow.implType)">
              <el-input v-model="formShow.attendeeNo" type="input" placeholder="暂无" :disabled="true" />
            </el-form-item>
            <el-form-item label-width="120" label="学习人员数" prop="attendeeNo" v-if="formShow.implType==2">
              <el-input style="width:100%" v-model="formShow.attendeeNo"  placeholder="暂无" :disabled="true" />
            </el-form-item>
            <el-form-item label-width="120" label="领导姓名" prop="leader" v-if="formShow.implType==3">
              <el-input style="width:100%" v-model="formShow.leaderName" placeholder="暂无" :disabled="true" />

            </el-form-item>
          </el-col><el-col :span="12">
            <el-form-item label="证明人" prop="certifier">
              <el-input style="width:100%" v-model="formShow.certifierName"  placeholder="暂无" :disabled="true" />
            </el-form-item>
           
          </el-col>
          <el-col :span="12">
          </el-col>
          <el-col :span="12">
            <el-form-item label="印证资料" prop="proof">
              <FileUpload :modelValue="formShow.proof" v-model="form.proof" :disabled="true" />
            </el-form-item>
          </el-col><el-col :span="24">
            <el-form-item label="落实描述" prop="implDescribe">
              <el-input v-model="formShow.implDescribe" type="textarea" :rows="6" placeholder="请输入内容" :disabled="true" />
            </el-form-item>

          </el-col></el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
  </div>
</template>

<script setup name="Offcial">
import { listOffcial, getOffcial, delOffcial, addOffcial, updateOffcial, getDeptList } from "@/api/coordination/offcial";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { coo_impl_type, coo_official_source } = proxy.useDict('coo_impl_type', 'coo_official_source');
import Viewer from "@/components/Custom/viewer.vue";

const baseUrl = import.meta.env.VITE_APP_BASE_API;

const offcialList = ref([]);
const fileViewerRef = ref()
const tbCooOfficialImplList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbCooOfficialImpl = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeSendTime = ref([]);
const implementList = ref([])
const selectId = ref()
const deptOptions = ref([])
const radioDept = ref("全部收费站")
const deptIds = ref([])
const dialogDoc = ref(false)
const isShow = ref(false)
const data = reactive({
  form: {},
  formShow: {},
  queryParams: {
    pageNum: 1,
    pageSize: 30,
    name: null,
    source: null,
    demand: null,
    sendTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules, formShow } = toRefs(data);

/** 查询公文管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeSendTime && '' != daterangeSendTime) {
    queryParams.value.params["beginSendTime"] = daterangeSendTime.value[0];
    queryParams.value.params["endSendTime"] = daterangeSendTime.value[1];
  }
  listOffcial(queryParams.value).then(response => {
    offcialList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    selectId.value = response.rows[0].id;
    getImplementList();
  });
}

/** 查询落实管理列表 */
function getImplementList() {
  if (!selectId.value) return;
  loading.value = true;
  getDeptList({ id: selectId.value }).then(response => {
    implementList.value = response.rows;
    // total.value = response.total;
    loading.value = false;
  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptIds.value = [];
  deptOptions.value = []
  deptTreeSelect().then(response => {
    let arr = response.data[0].children[0].children;
    arr.forEach(element => {
      // deptOptions.value.push(...element.children)
      element.children.forEach(opt => {
        deptIds.value.push(opt.id)
        deptOptions.value.push({ key: opt.id, value: opt.id, label: opt.label })
      })

    });


  });
};
// 取消按钮
function cancel() {
  open.value = false;
  isShow.value = false;
  reset();
}

const handleCurrentChange = (id) => {
  selectId.value = id;
  getImplementList();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    source: null,
    demand: null,
    sendTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  tbCooOfficialImplList.value = [];
  proxy.resetForm("offcialRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeSendTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加公文管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOffcial(_id).then(response => {
    form.value = response.data;
    tbCooOfficialImplList.value = response.data.tbCooOfficialImplList;
    radioDept.value = response.data.deptIds.length >= 30 ? '全部收费站' : "部分收费站";
    open.value = true;
    title.value = "修改公文管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["offcialRef"].validate(valid => {
    if (valid) {
      if (radioDept.value == "全部收费站") {
        form.value.deptIds = deptIds.value
      }
      form.value.tbCooOfficialImplList = tbCooOfficialImplList.value;
      if (form.value.id != null) {
        updateOffcial(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOffcial(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除公文管理编号为"' + _ids + '"的数据项？').then(function () {
    return delOffcial(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 公文落实情况上报序号 */
function rowTbCooOfficialImplIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 公文落实情况上报添加按钮操作 */
function handleAddTbCooOfficialImpl() {
  let obj = {};
  obj.deptId = "";
  obj.implType = "";
  obj.implDescribe = "";
  obj.proof = "";
  obj.certifier = "";
  obj.status = "";
  tbCooOfficialImplList.value.push(obj);
}

/** 公文落实情况上报删除按钮操作 */
function handleDeleteTbCooOfficialImpl() {
  if (checkedTbCooOfficialImpl.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的公文落实情况上报数据");
  } else {
    const tbCooOfficialImpls = tbCooOfficialImplList.value;
    const checkedTbCooOfficialImpls = checkedTbCooOfficialImpl.value;
    tbCooOfficialImplList.value = tbCooOfficialImpls.filter(function (item) {
      return checkedTbCooOfficialImpls.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTbCooOfficialImplSelectionChange(selection) {
  checkedTbCooOfficialImpl.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/offcial/export', {
    ...queryParams.value
  }, `公文管理_${new Date().getTime()}.xlsx`)
}
const handleShow = (data) => {
  formShow.value = data;
  isShow.value = true;

}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file && file.indexOf(',') == -1) {
    data.src = `${baseUrl}${file}`;
  } else if (file && file.indexOf(',') != -1) {
    let src = file.split(',')[0]
    data.src = `${baseUrl}${src}`;
    file = src
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '公文');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};

getList()
getDeptTree()
</script>

<style scoped>
.margin-bottom {
  margin-bottom: 10px;
}
.list {
  margin: 10px;
  cursor: pointer;
  padding: 15px;
  box-sizing: border-box;
  border: 1px solid #f5f5f5;
  box-shadow: 0 0 5px #f5f5f5;
  position: relative;
  border-radius: 10px;
  border: 1px solid #fff;
}
.list .flex {
  display: flex;
  align-items: center;
}
.between {
  justify-content: space-between;
  margin-bottom: 6px;
}
.list .serice {
  width: 20px;
  line-height: 20px;
  background: #246bcc;
  color: #fff;
  border-radius: 4px;
  text-align: center;
  font-size: 12px;
  margin-right: 6px;
}
.list .name {
  width: 400px;
  flex-shrink: 0;
  color: #246bcc;
  font-size: 16px;
  font-weight: 600;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.list .demand {
  font-size: 14px;
  color: #999;
  padding-left: 32px;
  line-height: 1.6;
  margin-top: 6px;
}
.list .time {
  font-size: 12px;
  color: #c7c7c7;
  line-height: 1.6;
  padding-left: 32px;
}
.list .text-theme {
  color: #246bcc;
  font-size: 30px;
}
.list .source {
  font-size: 16px;
  color: #333;
  margin-right: 6px;
}
.list .absolute {
  position: absolute;
  right: 20px;
  top: 50px;
  font-size: 22px;
  font-weight: 600;
  color: #999;
}
.empty-top {
  height: 10px;
}
.list.active {
  background: #e2eeff;
  border: 1px solid #246bcc;
}
</style>
